package com.example.rentsystem.servlet.auth;

import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.UserService;
import com.example.rentsystem.service.impl.UserServiceImpl;
import com.example.rentsystem.utils.ThymeleafUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.thymeleaf.context.Context;

import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/sign-up")
public class RegisterServlet extends HttpServlet {

    UserService service;

    @Override
    public void init() throws ServletException {
        service = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        // 已经登录
        if (session.getAttribute("user") != null) {
            resp.sendRedirect("index");
            return;
        }

        Context context = new Context();

        String signUpInfo = "创建您的账号进入网站";
        String signUpInfoStyle = "";
        if (session.getAttribute("password-not-equal") != null) {
            signUpInfo = "两次密码不一致";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("password-not-equal");
        } else if (session.getAttribute("signup-failure") != null) {
            signUpInfo = "注册失败, 可能原因: (信息输入不全或者账号重复)";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("signup-failure");
        } else if (session.getAttribute("username-exist") != null) {
            signUpInfo = "注册失败, 可能原因: (用户名重复)";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("username-exist");
        } else if (session.getAttribute("account-exist") != null) {
            signUpInfo = "注册失败, 可能原因: (账号重复)";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("account-exist");
        } else if (session.getAttribute("invalid-phone") != null) {
            signUpInfo = "注册失败, 请输入正确的手机号码";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("invalid-phone");
        } else if (session.getAttribute("password-short") != null) {
            signUpInfo = "注册失败, 可能原因: (密码长度应该在8到18位)";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("password-short");
        } else if (session.getAttribute("name-short") != null) {
            signUpInfo = "注册失败, 可能原因: (名字长度应该在2到6位)";
            signUpInfoStyle = "color: red;font-weight: bold;";
            session.removeAttribute("name-short");
        }

        context.setVariable("user", null);
        context.setVariable("sign_up_info", signUpInfo);
        context.setVariable("sign_up_info_style", signUpInfoStyle);

        ThymeleafUtil.process("sign-up.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();

        String username = req.getParameter("username");
        String account = req.getParameter("account");
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirm-password");
        String role = req.getParameter("role");
        if (isNull(username) || isNull(account) || isNull(phone) || isNull(password) || isNull(confirmPassword)) {
            session.setAttribute("signup-failure", true);
            this.doGet(req, resp);
            return;
        }
        if (isNull(role)) role = "user";
        if (service.userNameExist(username)) {
            session.setAttribute("username-exist", true);
            this.doGet(req, resp);
            return;
        }
        if (service.accountExist(account)) {
            session.setAttribute("account-exist", true);
            this.doGet(req, resp);
            return;
        }
        if (!isValidPhoneNumber(phone)) {
            session.setAttribute("invalid-phone", true);
            this.doGet(req, resp);
            return;
        }
        if (!(username.length() >= 2 && username.length() <= 6)) {
            session.setAttribute("name-short", true);
            this.doGet(req, resp);
            return;
        }
        if (!(password.length() >= 8 && password.length() <= 18)) {
            session.setAttribute("password-short", true);
            this.doGet(req, resp);
            return;
        }
        if (!password.equals(confirmPassword)) {
            session.setAttribute("password-not-equal", true);
            this.doGet(req, resp);
        } else {
            if (service.signup(User.builder()
                    .name(username)
                    .account(account)
                    .password(password)
                    .phone(phone)
                    .role(role)
                    .build())) {
                session.removeAttribute("signup-failure");
                resp.sendRedirect("login");
            } else {
                session.setAttribute("signup-failure", true);
                this.doGet(req, resp);
            }
        }
    }

    private boolean isNull(String s) {
        return s == null || s.equals("");
    }

    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }
}
